package top.mayyd.producteurekaconsumer.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import top.mayyd.producteurekaservice.domain.Product;

import java.util.List;
import java.util.Random;

@Service
public class ProductService {
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;


    public Product getById(Long id) {
        //根据服务名称 获取服务的实例
        /*List<ServiceInstance> instances = discoveryClient.getInstances("product-eureka-service");

        //这里由于只开启了一个，因此，直接使用第一个
        ServiceInstance instance = instances.get(0);

        //获取Ip 和 端口信息
        String url = "http://" + instance.getHost() + ":" + instance.getPort() + "/product/" + id;*/

        //采用Ribbon 负载均衡方式：直接通过服务名称调用
        String url = "http://product-eureka-service/product/" + id;

        Product product = restTemplate.getForObject(url, Product.class);
        System.out.println(product);
        return product;
    }


    /**
     * 结合熔断方式
     *
     * @param id
     * @return
     */
    public String getOne(Long id) {
        //采用Ribbon 负载均衡方式：直接通过服务名称调用
        String url = "http://product-eureka-service/product/" + id;
        String product = restTemplate.getForObject(url, String.class);
        System.out.println(product);
        return product;
    }


}
